<template>
  <div class="home-wrap">
    <div class="home-content">
      <span class="back-arrow" @click="handleBack"></span>
      <div class="home-head">
        <p class="checkcourse-title">
          <span @click="goCheckCourse">
            <span class="title-color">{{ reverseStatus.name || '请选择专题' }}</span>
            <a-icon class="base-color" type="right" />
          </span>
        </p>
      </div>
      <div class="home-center">
        <div class="study-left">
          <p @click="goGrammarStudy('0')">
            <span>{{ chapterDetail.today_num }} <i>句</i></span>
            <span>今日学习</span>
          </p>
          <p @click="goGrammarStudy('1')">
            <span>{{ chapterDetail.total_learning }} <i>句</i></span>
            <span>累计学习</span>
          </p>
        </div>
        <div class="study-check">
          <div
            class="rotate-wrap"
            :class="{
              'animat-step1': animat === 1,
            }"
          >
            <div class="grid-circle grid-circle1"></div>
            <div class="grid-circle grid-circle2"></div>
            <div class="grid-circle grid-circle3"></div>
            <div class="grid-circle grid-circle4"></div>
            <div
              class="reverse-star reverse-star1"
              :class="{
                'animat-step1': animat === 1,
              }"
              @click="goGrammarCheck"
            >
              <img src="~assets/reverse/index-green.png" alt="" />
              <span>{{ chapterDetail.green }}</span>
            </div>
            <div
              class="reverse-star reverse-star2"
              :class="{
                'animat-step1': animat === 1,
              }"
              @click="goReview('1')"
            >
              <img src="~assets/reverse/index-red.png" alt="" />
              <span>{{ chapterDetail.red }}</span>
            </div>
            <div
              class="reverse-star reverse-star4"
              :class="{
                'animat-step1': animat === 1,
              }"
              @click="goReview('2')"
            >
              <img src="~assets/reverse/index-yellow.png" alt="" />
              <span>{{ chapterDetail.yellow }}</span>
            </div>
            <div
              class="reverse-star reverse-star3"
              :class="{
                'animat-step1': animat === 1,
              }"
              @click="goReview('3')"
            >
              <img src="~assets/reverse/index-blue.png" alt="" />
              <span>{{ chapterDetail.purple }}</span>
            </div>
          </div>
          <div
            class="check-start"
            :class="{
              'animat-step2': animat === 2,
            }"
            @click="startClickHandle"
          >
            START
          </div>
        </div>
        <div class="study-right">
          <p>
            <span>{{ chapterDetail.total_time }} <i>m</i></span>
            <span>学习时长</span>
          </p>
          <p>
            <span>{{ chapterDetail.total_sentence }} <i>句</i></span>
            <span>句子总数</span>
          </p>
        </div>
      </div>
      <p class="home-bottom">
        <a @click="goSkill">考点解读</a>
        <a @click="moreClickHandle"><a-icon type="menu"/></a>
      </p>
    </div>
    <checkModal :visible.sync="checkModalVisible" @ok="goCheckCourse" />
    <moreModal
      :level="chapterDetail.level"
      :visible.sync="moreModalVisible"
      @choseClick="grammarChose"
    />
    <Timetips ref="timetips"></Timetips>
  </div>
</template>
<script>
import {
  fetchChapterDetail,
  fetchLastChapter,
  fetchRatioSentence,
} from "@/services/reverse";
import { startTime, stopTime } from '@/services/home.js'
import checkModal from "./checkModal";
import moreModal from "./moreModal";
import { SUCCESS_CODE } from "@/utils/const";
import { mapMutations, mapState } from "vuex";
import Timetips from "@/components/Timetips";
import _ from "lodash";
export default {
  name: "reverse",
  components: {
    checkModal,
    moreModal,
    Timetips,
  },
  data() {
    return {
      animat: "",
      chapterDetail: {},
      checkModalVisible: false,
      moreModalVisible: false,
      isBack: false,
      isEmpty: false,
      package_id: 0,
      last_package_id:sessionStorage.getItem('last_package_id')
    };
  },
  async created() {	  
	console.log('grammar start');
	console.log(this.$route.query);
    if (this.$route.query.isBack) {
      this.isBack = this.$route.query.isBack
    }
	this.package_id = this.$route.query.curr_id
	console.log('----------------------------',this.package_id);
	if(this.last_package_id != undefined && this.last_package_id > 0 && this.last_package_id != null){
		if(this.package_id != this.last_package_id){
			// this.stoptime();
			sessionStorage.setItem('last_package_id',this.package_id)
			this.last_package_id = this.package_id
			// this.starttime();
		}
	}else{
		sessionStorage.setItem('last_package_id',this.package_id)
		this.last_package_id = this.package_id
		// this.starttime();
	}
    await this.fetchLastChapter();
  },
  computed: {
    ...mapState(["reverseStatus"]),
  },
  methods: {
    ...mapMutations([
      "setReverseStatus",
      "setSentenceList",
      "setGrammarExplain",
    ]),
    startClickHandle() {
      this.$loading.show()
      this.animat = 1;
      setTimeout(() => {
        this.animat = 0
        if (this.isEmpty) {
          this.checkModalVisible = true
          this.$loading.hide()
        } else {
          this.fetchRatioSentence();
        }
      }, 600);
    },
    fetchRatioSentence() {
      fetchRatioSentence({
        chapter_id: this.reverseStatus.chapters_id,
        curr_id: this.reverseStatus.curr_id,
      }).then((res) => {
        this.$loading.hide()
        if (res.code === SUCCESS_CODE) {
          if (Array.isArray(res.data.list)) {
            let list = res.data.list.map((v) => {
              return Object.assign(v, { clickNum: 0 });
            });
            let sentenceList = Object.assign(res.data, { list });
            this.setSentenceList(sentenceList);
          }
          if (+res.data.type === 1) {
            // 去绿格
            this.$yxpConfirm({
              msg: "恭喜你完成本专题的学习，请找过关老师检测！",
            }).then(() => {
              this.$router
                .push({
                  path: "/reverse/grammar-check",
                  query: {
                    chapter_id: this.reverseStatus.chapters_id,
                    curr_id: this.reverseStatus.curr_id,
                  },
                })
                .catch(() => {});
            });
          }
          if (+res.data.type === 3) {
            console.log(res.data.url);
            this.$router.push({
              path: "/reverse/winding-report",
              query: {
                reportUrl: res.data.url,
              },
            });
            // https://newyxp.sse100.com/index/index/certificate?from=1&complete=3&chapter_id=119&student_id=32045&type=3
          }
          if (+res.data.type === 0) {
            // 0 且test为空跳转句子列表，test不为空
            if (!res.data.test.length) {
              this.$router.push({
                path: "/reverse/grammar-sentence",
                query: {
                  chapter_id: this.reverseStatus.chapters_id,
                  curr_id: this.reverseStatus.curr_id,
                  name: this.reverseStatus.name,
                },
              });
            } else {
              this.$router.push({
                path: "/reverse/group-test",
                query: { index: true },
              });
            }
          }
        }
      }).catch(() => {
        this.$loading.hide()
      });
    },
    async fetchLastChapter() {
      // reverse状态 还是放全局好(已route 为主)
      let { chapters_id, curr_id, name, pack_name } = this.$route.query;
		console.log('---------------------',this.$route.query);
      if (chapters_id && curr_id) {
        this.fetchChapterDetail({ chapters_id, curriculum_id: curr_id });
        this.setReverseStatus({
          chapters_id,
          curr_id,
          name,
          pack_name,
        });
      } else {
        await fetchLastChapter().then((res) => {
            console.log(res, '-=-=-=-')
          if (res.code === SUCCESS_CODE) {
            if (!_.get(res.data, "chapters_id", "")) {
              if (!_.get(res.data, "curriculum_id", "")) {
                // 如果没带参数过来 才弹框，课程仅是选择并不会记录到上次学习
                console.log('1111')
                this.setReverseStatus({})
                this.isEmpty = true
                if (!this.isBack) {
                  this.checkModalVisible = true;
                }
              }
            } else {
              this.setReverseStatus({
                chapters_id: _.get(res.data, "chapters_id", ""),
                curr_id: _.get(res.data, "curriculum_id", ""),
                name: _.get(res.data, "name", ""),
                pack_name: _.get(res.data, "pack_name", ""),
              });
              this.fetchChapterDetail({
                chapters_id: _.get(res.data, "chapters_id", ""),
                curriculum_id: _.get(res.data, "curriculum_id", ""),
              });
            }
          }
        });
      }
    },
    moreClickHandle() {
      if (this.isEmpty) {
        this.checkModalVisible = true
      } else {
         this.moreModalVisible = true
      }
    },
    fetchChapterDetail(data) {
      fetchChapterDetail(data).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.chapterDetail = res.data;
          this.setReverseStatus(
            Object.assign(this.reverseStatus, { level: res.data.level })
          );
        }
      });
    },
    goGrammarCheck() {
      this.$router.push({
        path: "/reverse/grammar-check",
        query: {
          chapter_id: this.reverseStatus.chapters_id,
          curr_id: this.reverseStatus.curr_id,
        },
      });
    },
    async goGrammarStudy(type) {
      // 0 今日， 1 累计
      let num =
        type === "0"
          ? this.chapterDetail.today_num
          : this.chapterDetail.total_learning;
      if (!num) {
        await this.$yxpConfirm({
          type: "alert",
          msg: "本章节今天您还没有学习",
        });
        return;
      }

      this.$router.push({
        path: "/reverse/grammar-study",
        query: {
          chapter_id: this.reverseStatus.chapters_id,
          curr_id: this.reverseStatus.curr_id,
          type: type,
        },
      });
    },
    goReview(type) {
      this.$router.push({
        path: "/reverse/grammar-review",
        query: {
          chapter_id: this.reverseStatus.chapters_id,
          curr_id: this.reverseStatus.curr_id,
          type: type,
        },
      });
    },
    goCheckCourse() {
      // this.checkModalVisible = false;
      this.$router.push({
        path: "/reverse/choseCourse",
        query: {
          chapter_id: this.reverseStatus.chapters_id,
          curr_id: this.reverseStatus.curr_id,
          title: this.reverseStatus.pack_name,
        },
      });
    },
    grammarChose(type) {
      if (type === "1") {
        this.$router.push({
          path: "/reverse/grammar-blank",
          query: {
            type: type,
          },
        });
      } else {
        this.$router.push({
          path: "/reverse/grammar-mistake",
          query: {
            type: type,
          },
        });
      }
      this.moreModalVisible = false;
    },
    goSkill() {
      if (this.reverseStatus.chapters_id) {
        this.setGrammarExplain(true);
      } else {
        this.$message.error('请选择专题~')
      }
    },
async starttime () {
  let params = {
	package_id: this.package_id
  }
  let data = await startTime(params)
  if (data.code === 1) {
	console.log('start time success');
  } else {	
	this.$toast(data.info);
	console.log('start time fail');
	sessionStorage.setItem('last_package_id',0)
	this.last_package_id = 0;
	this.$router.replace({
		path: '/'
	})
	return false;
  }
},
	async stoptime () {
		// let params = {
		// 	package_id: this.last_package_id
		// }
		// let data = await stopTime(params)
		// if (data.code === 1) {
		// 	console.log('stop time success');
		// } else {
		// 	console.log('stop time fail');
		// }
	},
	handleBack () {
		// this.stoptime();
		sessionStorage.setItem('last_package_id',0)
		this.last_package_id = 0;
		this.$router.replace({
			path: '/'
		})
	}
  },
  mounted() {},
  
  beforeDestroy() {
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
};
</script>
<style lang="less">
@import url("./index.less");
</style>
